package com.example.demo.course.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.demo.course.Course;
import com.example.demo.course.UserCourse;
import com.example.demo.course.dto.CourseExcelDTO;
import com.example.demo.course.service.CourseService;
import com.example.demo.course.repository.UserCourseRepository;

import java.util.ArrayList;
import java.util.List;

public class CourseExcelListener extends AnalysisEventListener<CourseExcelDTO> {

    private final CourseService courseService;
    private final Long userId;
    private final UserCourseRepository userCourseRepository;
    private List<Course> courses = new ArrayList<>();

    public CourseExcelListener(CourseService courseService, Long userId, UserCourseRepository userCourseRepository) {
        this.courseService = courseService;
        this.userId = userId;
        this.userCourseRepository = userCourseRepository;
    }

    @Override
    public void invoke(CourseExcelDTO data, AnalysisContext context) {
        Course course = new Course();
        course.setName(data.getName());
        course.setTime(data.getTime());
        course.setLocation(data.getLocation());
        course.setTeacher(data.getTeacher());
        courses.add(course);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 批量保存课程
        List<Course> savedCourses = courseService.saveBatchCourses(courses);

        // 保存用户 - 课程关联信息
        for (Course course : savedCourses) {
            UserCourse userCourse = new UserCourse();
            userCourse.setUserId(userId);
            userCourse.setCourseId(course.getId());
            userCourseRepository.save(userCourse);
        }
    }

    public void doAfterAllAnalysed() {
        System.out.println("成功");
    }
}
